#include "HttpRequest.h"
#include <QEventLoop>

QString HttpRequest::Post(QString url, QString str){
    request.setUrl(QUrl(url));

    QString sNode = str;
    reply = this->post(request, sNode.toUtf8());

    QEventLoop eventLoop;
    connect(this, &HttpRequest::finished, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();

    if(reply->error())
        qDebug() << QString(reply->errorString());
    return QString(reply->readAll());
}

QString HttpRequest::PostJson(QString url, QJsonObject json, bool wait){
    request.setUrl(QUrl(url));

    QString data = QJsonDocument(json).toJson(QJsonDocument::Compact);
    reply = this->post(request, data.toUtf8());

    if(wait){
        QEventLoop eventLoop;
        connect(this, &HttpRequest::finished, &eventLoop, &QEventLoop::quit);
        eventLoop.exec();
    }

    if(reply->error())
        qDebug() << QString(reply->errorString());
    return QString(reply->readAll());
}

QString HttpRequest::Get(QString url){
    request.setUrl(QUrl(url));
    reply = this->get(request);

    QEventLoop eventLoop;
    connect(this, &HttpRequest::finished, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();

    if(reply->error())
        qDebug() << QString(reply->errorString());
    return QString(reply->readAll());

}

QString HttpRequest::Delete(QString url){
    request.setUrl(QUrl(url));
    reply = this->deleteResource(request);

    QEventLoop eventLoop;
    connect(this, &HttpRequest::finished, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();

    if(reply->error())
        qDebug() << QString(reply->errorString());
    return QString(reply->readAll());
}

void HttpRequest::Patch(QString url, QJsonObject json){
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    request.setUrl(QUrl(url));
    buffer.open((QBuffer::ReadWrite));
    QString data = QJsonDocument(json).toJson(QJsonDocument::Compact);
    buffer.write(data.toUtf8());
    buffer.seek(0);
    this->sendCustomRequest(request, "PATCH", &buffer);

    /*
    QEventLoop eventLoop;
    connect(this, &HttpRequest::finished, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();

    if(reply->error())
        qDebug() << QString(reply->errorString());
    return QString(reply->readAll());
    */
}
